package com.mission.schedule.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lcf.refreshlibrary.PullToRefreshBase;
import com.lcf.refreshlibrary.PullToRefreshListView;
import com.lcf.refreshlibrary.PullToRefreshScrollView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.R;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.fragment.NewMyFoundFragment;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.ListViewForScrollView;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.Utils;
import com.mission.schedule.widget.SwipeLinearLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * Created by liwei on 2017/5/31.
 */

public class QDFXGLListActivity extends BaseActivity {

    PullToRefreshListView pullToRefreshListView;
    LinearLayout top_ll_back;
    TextView title;

    int flag = 0;
    int style = 0;

    SharedPrefUtil sharedPrefUtil;
    List<NewMyFoundFragment.PubicBytitle.ListBean> listBeanList = new ArrayList<>();

    ListAdpater listAdpater;

    String admin = "0";
    String titleid = "";

    @Override
    protected void setListener() {
        top_ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.qdfx_detail_list);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        sharedPrefUtil = new SharedPrefUtil(this, ShareFile.USERFILE);
        userID = sharedPrefUtil.getString(this, ShareFile.USERFILE, ShareFile.USERID, "");
        admin = sharedPrefUtil.getString(this, ShareFile.USERFILE, ShareFile.ISADMIN, "0");
        top_ll_back = (LinearLayout) findViewById(R.id.top_ll_back);
        title = (TextView) findViewById(R.id.title);
        title.setText("轮播清单");
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listview);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);

        getData(true);
    }

    @Override
    protected void setAdapter() {
    }

    private Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Collections.sort(listBeanList, new Comparator<NewMyFoundFragment.PubicBytitle.ListBean>() {
                        @Override
                        public int compare(NewMyFoundFragment.PubicBytitle.ListBean lhs,
                                           NewMyFoundFragment.PubicBytitle.ListBean rhs) {
                            return DateUtil.parseDateTimeSs(lhs.changeTime.replace('T',' '))
                                    .before(DateUtil.parseDateTimeSs(rhs.changeTime.replace('T',' '))) ? 1 : -1;
                        }
                    });
                    listAdpater = new ListAdpater(listBeanList, style);
                    pullToRefreshListView.setAdapter(listAdpater);
                    listAdpater.notifyDataSetChanged();
                    break;
            }
        }
    };

    private void send(int what) {
        Message message = new Message();
        message.what = what;
        hander.sendMessage(message);
    }


    String userID;
    ProgressUtil progressUtil = new ProgressUtil();

    private void getData(final boolean isF) {
        if (isF) {
            progressUtil.ShowProgress(QDFXGLListActivity.this, true, true, "正在下载...");
        }
        HttpUtils httpUtils = new HttpUtils(10000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("nowPage", "1");
        params.addBodyParameter("pageNum", "20");
        httpUtils.send(HttpMethod.POST, URLConstants.清单发现分组标题查询, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    Gson gson = new Gson();


                    NewMyFoundFragment.PubicBytitle publiByTitle = gson.fromJson(responseInfo.result, NewMyFoundFragment.PubicBytitle.class);
                    if (publiByTitle.status == 0) {
                        listBeanList.clear();
                        listBeanList.addAll(publiByTitle.list);
                        send(1);
                    }
                }
                if (isF) {
                    progressUtil.dismiss();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                if (isF) {
                    progressUtil.dismiss();
                }
                Toast.makeText(QDFXGLListActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
            }
        });

    }


    private void updateQDFX(int type, String num,final int position,String userid) {
        progressUtil.ShowProgress(QDFXGLListActivity.this, true, true, "修改中...");
        HttpUtils httpUtils = new HttpUtils(10000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("type", "" + type);
        params.addBodyParameter("num", num);
        params.addBodyParameter("uId", userid);
        httpUtils.send(HttpMethod.POST, URLConstants.清单发现清单修改, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    Gson gson = new Gson();
                    updateQDFXBean bean = gson.fromJson(responseInfo.result, updateQDFXBean.class);
                    if (bean.status == 0){
                        Toast.makeText(QDFXGLListActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                        listAdpater.top(position);
                    }else {
                        Toast.makeText(QDFXGLListActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                    }
                }
                progressUtil.dismiss();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                progressUtil.dismiss();
                Toast.makeText(QDFXGLListActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void deleteQDFX(String num,final int position,String userid) {
        progressUtil.ShowProgress(QDFXGLListActivity.this, true, true, "删除中...");
        HttpUtils httpUtils = new HttpUtils(10000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("num", num);
        params.addBodyParameter("uId", userid);
        httpUtils.send(HttpMethod.POST, URLConstants.清单发现删除清单, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    Toast.makeText(QDFXGLListActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    listBeanList.remove(position);
                    listAdpater.notifyDataSetChanged();
                }
                progressUtil.dismiss();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                progressUtil.dismiss();
                Toast.makeText(QDFXGLListActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 推荐清单右滑对话框
     */
    private void alterPushDialog(final String num,final String userid,final int position) {
        final Dialog dialog = new Dialog(QDFXGLListActivity.this, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(QDFXGLListActivity.this);
        View more_pop_menu = fac.inflate(R.layout.dialog_qdfx_push_gl, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();
        more_pop_menu.findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                updateQDFX(4, num,position,userid);
            }
        });
        more_pop_menu.findViewById(R.id.top).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                updateQDFX(1, num,position,userid);
            }
        });
        more_pop_menu.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                deleteQDFX(num,position,userid);
            }
        });
        more_pop_menu.findViewById(R.id.canel_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

    }


    public class ListAdpater extends BaseAdapter {
        List<NewMyFoundFragment.PubicBytitle.ListBean> list;
        int style = 0;
        List<SwipeLinearLayout> swipeLinearLayouts = new ArrayList<>();

        public ListAdpater(List<NewMyFoundFragment.PubicBytitle.ListBean> list, int style) {
            this.list = list;
            this.style = style;
        }

        public void delete(int position){
            this.list.remove(position);
            notifyDataSetChanged();
        }

        public void top(int position){
            NewMyFoundFragment.PubicBytitle.ListBean bean = list.get(position);
            list.remove(position);
            list.add(0,bean);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(QDFXGLListActivity.this).inflate(R.layout.adapter_fxdlist, parent, false);
                holder.title = (TextView) convertView.findViewById(R.id.title);
                holder.name = (TextView) convertView.findViewById(R.id.time);
                holder.other = (TextView) convertView.findViewById(R.id.share);

                holder.more = (LinearLayout) convertView.findViewById(R.id.more);
                holder.delete = (TextView) convertView.findViewById(R.id.delete);

                holder.sw_ll = (SwipeLinearLayout) convertView.findViewById(R.id.swipeLayout);
                holder.more_ll = (RelativeLayout) convertView.findViewById(R.id.more_ll);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            swipeLinearLayouts.add(holder.sw_ll);
            holder.sw_ll.setOnSwipeListener(new SwipeLinearLayout.OnSwipeListener() {
                @Override
                public void onDirectionJudged(SwipeLinearLayout thisSll, boolean isHorizontal) {
                    if (false == isHorizontal) {
                        for (SwipeLinearLayout sll : swipeLinearLayouts) {
                            if (null == sll) {
                                continue;
                            }
                            sll.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
                        }
                    } else {
                        for (SwipeLinearLayout sll : swipeLinearLayouts) {
                            if (null == sll) {
                                continue;
                            }
                            if (!sll.equals(thisSll)) {
                                //划开一个sll， 其他收缩
                                sll.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
                            }
                        }
                    }
                }
            });

            if (admin.equals("0")) {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        Utils.dipTopx(QDFXGLListActivity.this, 0), RelativeLayout.LayoutParams.MATCH_PARENT);
                holder.more_ll.setLayoutParams(params);
            } else {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        Utils.dipTopx(QDFXGLListActivity.this, 90), RelativeLayout.LayoutParams.MATCH_PARENT);
                holder.more_ll.setLayoutParams(params);
            }

            holder.delete.setVisibility(View.GONE);
            holder.more.setVisibility(View.VISIBLE);

            holder.more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    holder.sw_ll.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
                    alterPushDialog(list.get(position).num,list.get(position).uid+"", position);
                }
            });

            holder.sw_ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(QDFXGLListActivity.this, QDFXDetailActivity.class);
                    intent.putExtra("title", listBeanList.get(position).titles);
                    intent.putExtra("titleId", listBeanList.get(position).titleId);
                    intent.putExtra("path", listBeanList.get(position).imgPath);
                    intent.putExtra("goodNum", listBeanList.get(position).goodNum + "");
                    intent.putExtra("redNum", listBeanList.get(position).redNum + "");
                    intent.putExtra("name", listBeanList.get(position).uname);
                    intent.putExtra("time", listBeanList.get(position).createTime);
                    intent.putExtra("num", listBeanList.get(position).num + "");
                    intent.putExtra("uid", listBeanList.get(position).uid + "");
                    intent.putExtra("stylee", listBeanList.get(position).style);
                    intent.putExtra("type",5);
                    startActivity(intent);
                }
            });


            if (list.size() > 0) {

                if (position == 0){
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    params.setMargins(0,Utils.dipTopx(QDFXGLListActivity.this,20),0,0);
                    holder.sw_ll.setLayoutParams(params);
                } else if (position == list.size() -1){
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    params.setMargins(0,0,0,Utils.dipTopx(QDFXGLListActivity.this,20));
                    holder.sw_ll.setLayoutParams(params);
                }

                holder.title.setText(list.get(position).titles);
                holder.name.setText("@" + list.get(position).uname);
                if (style == 0) {
                    Date createTime = DateUtil.parseDateTimeSs(list.get(position).createTime.replace('T', ' '));
                    Date dateToday = DateUtil.parseDateTime(DateUtil.formatDateTimeSs(new Date()));
                    long betweem = (long) (createTime.getTime() - dateToday.getTime()) / 1000;
                    long day = betweem / (24 * 3600);
                    long hour = betweem % (24 * 3600) / 3600;
                    long min = betweem % 3600 / 60;
                    if (Math.abs(day) >= 1) {
                        holder.other.setText(Math.abs(day) + "天前");
                    } else {
                        if (Math.abs(hour) >= 1) {
                            holder.other.setText(Math.abs(hour) + "小时前");
                        } else {
                            holder.other.setText(Math.abs(min) + "分钟前");
                        }
                    }
                } else if (style == 1) {
                    holder.other.setText("浏览" + list.get(position).redNum + "  赞" + list.get(position).goodNum);
                }
            }

            return convertView;
        }

        class ViewHolder {
            TextView title, name, other, delete;
            LinearLayout more;
            RelativeLayout more_ll;
            SwipeLinearLayout sw_ll;
        }
    }

    public class updateQDFXBean{

        /**
         * delList : null
         * downTime : 2017-06-01T15:40:01
         * list : null
         * message : 失败
         * status : 1
         * tDelList : null
         */

        public Object delList;
        public String downTime;
        public Object list;
        public String message;
        public int status;
        public Object tDelList;

        public Object getDelList() {
            return delList;
        }

        public void setDelList(Object delList) {
            this.delList = delList;
        }

        public String getDownTime() {
            return downTime;
        }

        public void setDownTime(String downTime) {
            this.downTime = downTime;
        }

        public Object getList() {
            return list;
        }

        public void setList(Object list) {
            this.list = list;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public Object getTDelList() {
            return tDelList;
        }

        public void setTDelList(Object tDelList) {
            this.tDelList = tDelList;
        }
    }


}
